package com.newway.wechat.inteceptor;

import com.newway.LoginUser;
import com.newway.exception.ExceptionEnum;
import com.newway.util.JwtTokenUtil;
import com.newway.exception.UserInfoException;
import com.newway.wechat.context.UserInfoContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * 暂时不处理token过期 默认永久有效
 */
@Component
public class WechatUserInfoInterceptor implements HandlerInterceptor {

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tenantId = request.getHeader("X-Tenant-ID");
        String method = request.getMethod();
        if("OPTIONS".equals(method)){
            return true;
        }
        LoginUser loginUser = jwtTokenUtil.getLoginUser(request);
        if(loginUser!=null){
            jwtTokenUtil.verifyToken(loginUser);
            UserInfoContext.putUserInfo(loginUser.getUserInfo());
            return true;
        }
        throw new UserInfoException(ExceptionEnum.INVALID_TOKEN_EXCEPTION.code,ExceptionEnum.INVALID_TOKEN_EXCEPTION.msg);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoContext.removeUserInfo();
    }
}
